<template>
  <div>
    <head-tool>
      <template #right>
        <!-- 我在这里封装的函数，就只能在这个页面用，而别的页面也要用 -->
        <!-- 所以这个函数应该封装成全局的 Vue.prototype.$xxx = 函数  -->
        <!-- mixin： 混入 -->
        <el-button
          v-if="CHECK_POINT('EMP_EXPORT')"
          type="success"
          size="small"
          @click="doExport"
        >导出excel</el-button>
        <el-button
          v-if="CHECK_POINT('EMP_IMPORT')"
          type="primary"
          size="small"
          @click="$router.push('/import?type=employees')"
        >导入</el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="doAdd"
        >新增员工</el-button>
      </template>
    </head-tool>

    <el-card style="margin-top:30px;">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50" :index="fn" />
        <el-table-column prop="username" label="姓名" width="120" />
        <el-table-column prop="staffPhoto" label="头像" width="120">
          <template v-slot="{ row }">
            <img
              v-imgerr="defaultImg"
              style="width:80px;border-radius:50%;"
              :src="row.staffPhoto"
              alt=""
              @click="drawQr(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="120" />
        <el-table-column prop="workNumber" label="工号" width="120" />
        <el-table-column prop="formOfEmployment" label="聘用形式" width="120">
          <template v-slot="{ row }">
            {{ row.formOfEmployment | formatHireType }}
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门" width="120" />
        <el-table-column prop="timeOfEntry" label="入职时间" width="120" />

        <el-table-column prop="enableState" label="状态" width="120" />
        <el-table-column fixed="right" label="操作" width="230">
          <template v-slot="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
            <el-button
              type="text"
              size="small"
              @click="del(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="text-align:center;"
        :current-page.sync="pageInfo.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size.sync="pageInfo.size"
        layout=" total,sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        @current-change="getData"
        @size-change="getData"
      />
    </el-card>

    <emp-dialog ref="emp" @reload="getData" />

    <!-- 准备一个二维码对话框 -->
    <el-dialog title="扫码预览" :visible.sync="qrShow">
      <!-- 画板 -->
      <canvas ref="canvas" />
    </el-dialog>

    <!-- 分配角色对话框 -->
    <assign-role ref="role" />
  </div>
</template>

<script>
import { empListAPI, delEmpAPI } from '@/api/employees'
import enumObj from '@/utils/constant/employees'
import EmpDialog from './components/EmpDialog'
import AssignRole from './components/AssignRole.vue'
import QRCode from 'qrcode'

export default {
  name: 'Employees',
  components: {
    EmpDialog,
    AssignRole
  },
  filters: {
    formatHireType(val) {
      return enumObj.hireType.find(v => v.id.toString() === val.toString())
        .value
    }
  },
  data() {
    return {
      defaultImg: require('@/assets/common/head.jpg'),
      tableData: [],
      qrShow: false,
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    showRole(id) {
      // 调用即可
      this.$refs.role.show(id)
    },
    drawQr(url) {
      // 显示对话框 -- dom渲染是异步的
      this.qrShow = true
      this.$nextTick(() => {
        // 画二维码
        QRCode.toCanvas(this.$refs.canvas, url)
      })
    },
    async getData() {
      const res = await empListAPI(this.pageInfo)
      this.tableData = res.data.rows
      this.pageInfo.total = res.data.total
    },

    fn(index) {
      return (this.pageInfo.page - 1) * this.pageInfo.size + index + 1
    },
    // 删除
    del(id) {
      // 弹出确认框
      this.$confirm('是否删除该员工').then(async() => {
        await delEmpAPI(id)
        this.$message.success('删除成功')
        // 判断如果是最后一页并且只有一条数据，那就要刷新上一页
        const totalPage = Math.ceil(this.pageInfo.total / this.pageInfo.size)
        if (this.pageInfo.page === totalPage && this.tableData.length === 1) {
          this.pageInfo.page--
        }

        this.getData()
      })
    },

    // 添加
    doAdd() {
      this.$refs.emp.show = true
    },
    // 导出的点击事件
    doExport() {
      // 懒加载文件，当导入成功这个文件就会调用.then
      // 这个参数就是这个文件里暴露的对象
      // 相当于写的是：import excel from '@/vendor/Export2Excel'
      import('@/vendor/Export2Excel').then(async excel => {
        // 发请求
        const res = await empListAPI({
          page: 1,
          size: this.pageInfo.total
        })

        // 准备字典
        const userRelations = {
          入职日期: 'timeOfEntry',
          手机号: 'mobile',
          姓名: 'username',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          聘用形式: 'formOfEmployment',
          部门名称: 'departmentName'
        }

        // 准备表头
        const header = Object.keys(userRelations)

        // 准备数据
        const data = res.data.rows.map(v => {
          const list = []
          // 遍历字典
          for (const zhKey in userRelations) {
            // 取出对应的英文
            const enKey = userRelations[zhKey]
            list.push(v[enKey])
          }
          return list
        })

        // 调用这个方法就可以导出一个excel文件
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '传智播客员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    }

    // formatHireType(type) {
    //   // 打印参数，并打印参数的类型
    //   return enumObj.hireType.find(v => v.id.toString() === type.toString()).value
    // }
  }
}
</script>

<style></style>
